//
// Created by HP on 2025/11/19.
//

#include "Check.h"
#include <iostream>

// 检票状态常量定义
const std::string CheckStatus::NotChecked = "notChecked";
const std::string CheckStatus::Checked = "checked";
const std::string CheckStatus::Cancelled = "cancelled";

Check::Check() : Model("checks") {
    this->status = CheckStatus::NotChecked;
    setTableDefault("point_id", "VARCHAR(50) NOT NULL");
    setTableDefault("ticket_id", "VARCHAR(50) NOT NULL");
    setTableDefault("station_id", "VARCHAR(50) NOT NULL");
    setTableDefault("status", "VARCHAR(50) NOT NULL");
    setTableDefault("createdAt", "DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP");
}

void Check::bind(const std::string& key, const std::string& value) {
    if (!TableCols.count(key)) {
        std::cerr << "Error: Invalid key for check bind" << std::endl;
        return;
    }
    
    std::string selectSql = "SELECT * FROM " + TableName + " WHERE " + key + " = '" + Model::escapeSqlLiteral(value) + "';";
    std::vector<std::map<std::string, std::string>> result = DBConnector::getInstance()->query(selectSql);

    if (result.empty()) {
        std::cerr << "bind failed: SQL execution error or no result. SQL: " << selectSql << std::endl;
        return;
    }

    std::cout << "bind success. Table: " << TableName << std::endl;

    if (result.size() > 1) {
        std::cerr << "Error: Multiple checks found with the same " << key << std::endl;
        return;
    } else if (result.size() == 1) {
        this->id = result[0]["id"];
        this->point_id = result[0]["point_id"];
        this->ticket_id = result[0]["ticket_id"];
        this->status = result[0]["status"];
        this->createdAt = result[0]["createdAt"];
        this->isBind = true;
    }
}

bool Check::save() {
    std::string insertSql = "INSERT INTO " + TableName + " (point_id, ticket_id, status) VALUES ('" 
                          + Model::escapeSqlLiteral(point_id) + "', '" 
                          + Model::escapeSqlLiteral(ticket_id) + "', '" 
                          + Model::escapeSqlLiteral(status) + "');";
    
    int executeCode = DBConnector::getInstance()->execute(insertSql);
    if (executeCode == -1) {
        std::cerr << "save check failed: SQL execution error. SQL: " << insertSql << std::endl;
        std::cerr << "Database error: " << DBConnector::getInstance()->getError() << std::endl;
        return false;
    } else {
        std::cout << "save check success. Table: " << TableName << std::endl;
        return true;
    }
}
